package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.BookDTO;
import com.sky.dto.BookPageQueryDTO;
import com.sky.entity.Book;
import com.sky.exception.BookNotFoundException;
import com.sky.exception.BookOperationException;
import com.sky.mapper.BookMapper;
import com.sky.result.PageResult;
import com.sky.service.BookService;
import com.sky.vo.BookVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Description: 实现书籍相关功能
 * @Author: Qiuyan
 * @Date: 2025-04-13 10:28
 * @Version： 1.0
 **/

/**
 * 书籍管理服务
 */
@Service
@Slf4j
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    /**
     * 新增书籍
     * @param bookDTO
     */
    @Override
    @Transactional
    public void saveWithImage(BookDTO bookDTO) {
        Book book = new Book();
        BeanUtils.copyProperties(bookDTO, book);

        //设置默认状态为Available
        book.setAvailabilityStatus("Available");
        
        //插入书籍数据
        bookMapper.insert(book);
    }

    /**
     * 书籍分页查询
     * @param bookPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(BookPageQueryDTO bookPageQueryDTO) {
        PageHelper.startPage(bookPageQueryDTO.getPage(), bookPageQueryDTO.getPageSize());
        
        Page<BookVO> page = bookMapper.pageQuery(bookPageQueryDTO);
        
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 更新书籍状态
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(String status, Long id) {
        // 获取当前书籍信息
        Book book = bookMapper.getById(id);
        if (book == null) {
            throw new BookNotFoundException("书籍不存在");
        }

        // 检查库存并更新状态
        if ("Lent".equals(status)) {
            if (book.getStock() <= 0) {
                throw new BookOperationException("库存不足，无法借出");
            }
            // 减少库存
            book.setStock(book.getStock() - 1);
        } else if ("Available".equals(status)) {
            // 增加库存
            book.setStock(book.getStock() + 1);
        }

        // 更新状态
        Book bookToUpdate = Book.builder()
                .bookId(id)
                .availabilityStatus(status)
                .stock(book.getStock())
                .build();

        bookMapper.update(bookToUpdate);
    }
}
